class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution725 {
    public ListNode[] splitListToParts(ListNode head, int k) {
        ListNode temp = head;
        // 获得list长度
        int len = 0;
        while (temp != null) {
            len++;
            temp = temp.next;
        }
        if (len <= k) {
            ListNode[] ans = new ListNode[k];
            for (int i = 0; i < len; i++) {
                ans[i] = head;
                head = head.next;
            }
            for (int i = len; i < k; i++) {
                ans[i] = null;
            }
            for (int i = 0; i < k; i++) {
                if (ans[i] != null)
                    ans[i].next = null;
            }
            return ans;
        } else {
            ListNode[] ans = new ListNode[k];
            int average = len / k;
            int left = len % k;
            int cur = 0;
            int i;
            for (i = 0; i < left; i++) {
                ListNode t=head;
                ans[i] = t;
                while (cur < average) {
                    head = head.next;
                    t=t.next;
                    cur++;
                }
                head = head.next;
                t.next=null;
                cur = 0;
            }
            while (i < k) {
                ListNode t=head;
                ans[i] = t;
                for (int j = 0; j < average; j++) {
                    if(head.next!=null && t!=null) {
                        head = head.next;
                        t = t.next;
                    }
                }
                if(t!=null) t.next=null;
                i++;
            }
            return ans;
        }
    }
}